from rest_framework.serializers import ModelSerializer as MSerializer, ListSerializer as LSerializer


class ModelSerializer(MSerializer):
    """
    ### 自定义要序列化的字段

    """

    def __init__(self, *args, **kwargs):
        fields = kwargs.pop('fields', None)
        super(ModelSerializer, self).__init__(*args, **kwargs)
        if fields is not None:
            allowed = set(fields)
            existing = set(self.fields)
            for field in existing - allowed:
                self.fields.pop(field)


class TimestampModelSerializer(ModelSerializer):
    """
    ### 自动转换微妙时间戳
    """

    def to_representation(self, instance):
        res = super(TimestampModelSerializer, self).to_representation(instance)
        for key in res.keys():
            if str(key).endswith('_timestamp'):
                res[key] = res[key] / 1000
        return res
